import java.sql.*;

public class User {
    public int id = -1;
    public String username;
    public boolean loggedIn = false;

    public User() {
    }

    public boolean has(String username) {
        int this_id = -1;
        Connection conn = null;
        ResultSet rs = null;
        String query;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://www.guoruiming.com:3306/reservations?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC", "root", "123456");
            Statement stmt = conn.createStatement();
            query = "SELECT * FROM users WHERE username='" + username + "';";
            System.out.println(query);
            rs = stmt.executeQuery(query);
            try {
                if (rs.next()) {
                    return true;
                } else return false;
            } catch (SQLException e) {
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean login(String username, String password) {
        Connection conn = null;
        ResultSet rs = null;
        String query;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://www.guoruiming.com:3306/reservations?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC", "root", "123456");
            Statement stmt = conn.createStatement();
            query = "SELECT * FROM users WHERE username='" + username + "' and password='" + password + "';";
            System.out.println(query);
            rs = stmt.executeQuery(query);
            try {
                if (rs.next()) {
                    id = rs.getInt("id");
                    this.username = username;
                    loggedIn = true;
                    System.out.println(id);
                }
            } catch (SQLException e) {
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (id == -1) {
            System.out.println("登录失败，用户名或密码错误！");
            return false;
        } else return true;
    }
}
